import java.util.Arrays;

public class Solution188 {
    public int maxProfit(int k, int[] prices) {
        if (prices.length < 2 || k == 0) {
            return 0;
        }
        if (k > prices.length / 2) {
            return maxProfit(prices);
        }
        int[] dp = new int[2 * k];    //dp[i]表示进行第i次操作后的最大利润,买入和卖出各算一次
        Arrays.fill(dp, Integer.MIN_VALUE);
        for (int price : prices) {
            dp[0] = Math.max(dp[0], -price);
            for (int j = 1; j < dp.length; j++) {
                int t = j % 2 == 0 ? -price : price;
                dp[j] = Math.max(dp[j], dp[j - 1] + t);
            }
        }
        return dp[2 * k - 1];
    }

    int maxProfit(int[] prices) {
        int res = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1]) {
                res += prices[i] - prices[i - 1];
            }
        }
        return res;
    }
}
